package com.eiletxie.springcloud.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;


@Component
public class MyPredicateFactory extends AbstractRoutePredicateFactory<MyPredicateFactory.Config> {


    /**
     * cookie key.
     */
    public static final String NAME = "name";
    /**
     * cookie value key.
     */
    public static final String VALUE = "value";
    public MyPredicateFactory() {
        super(MyPredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(NAME,VALUE);
    }

    /*@Override
    public ShortcutType shortcutType() {
        return ShortcutType.GATHER_LIST;
    }*/

    @Override
    public Predicate<ServerWebExchange> apply(MyPredicateFactory.Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                ServerHttpRequest request = exchange.getRequest();

                List<String> strings = request.getQueryParams().get(config.getName());
                boolean b = strings.stream().anyMatch(
                        value -> value.equalsIgnoreCase(config.getValue()));
                System.out.println(b);
                return  b;
            }

            @Override
            public String toString() {
                return String.format("Methods: %s",config.getName());
            }
        };
    }
    @Validated
    public static class Config {

        private String name;

        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
}
